package u1project.server;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.*;
import u1project.common.Response;
import u1project.common.User;

/**
 * @author oldliu
 * @since 1.0
 */
public class UserManager {
    //用XMLEncoder格式的Xml存储用户信息
    private List<User> users=new ArrayList(0);
    public  static final String PATH="users.xml";
    public UserManager(){
        //初始化用户集合
        try {
            XMLDecoder xd=new XMLDecoder(new FileInputStream(PATH));
            users= (List<User>) xd.readObject();
            xd.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public Response register(String name,String pass,String pass2){
        Response resp = new Response();
        User u=new User(name,pass,null);
        if (!pass.equals(pass2)) {
            resp.setSuccess(false);
            resp.setMsg("两次密码不一致！");
        } else if (pass.length() < 5) {
            resp.setSuccess(false);
            resp.setMsg("密码太短！");
        } else if (users.contains(u)) {
            resp.setSuccess(false);
            resp.setMsg("用户名已经被使用！");
        } else {
            resp.setSuccess(true);
            resp.setMsg("注册成功");
            this.users.add(u);
            //
            saveUsers();
        }
        return resp;
    }
    public void saveUsers(){
        try {
            XMLEncoder xe=new XMLEncoder(new FileOutputStream(PATH));
            xe.writeObject(this.users);
            xe.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
